package com.example.esaclient;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer.FillOutsideLine;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Paging;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.RequestAsyncTask;
import com.facebook.RequestBatch;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphObject;

public class InsightsActivity extends Activity {
	TextView t1 ;
	TextView t2 ;		
	GlobalSettings gs;
	AlertDialogManager alert;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.insights);
		
		 t1 = (TextView)findViewById(R.id.txtMetric1);
		 t2 = (TextView)findViewById(R.id.txtMetric2);	
	
		t1.setText("Loading Graph....");
		t1.requestFocus();
		
	
		t2.setText("Loading Graph....");
			 gs = new GlobalSettings(this);
		 alert =  new AlertDialogManager();
		
		

		if(gs.getPrefBool(gs.PREF_KEY_FACEBOOK_LOGIN))		
		getFBMetrics();
		else{
			alert.showAlertDialog(this,
					"Not connected to Facebook",
					"You must have an active Facebook account associated to ESA to get the insights.", false);
		}
		if(gs.getPrefBool(gs.PREF_KEY_TWITTER_LOGIN))		
		getTWMetrics();
		else{
			alert.showAlertDialog(this,
					"Not connected to Twitter",
					"You must have an active Twitter account associated to ESA to get the insights.", false);
		}
		
	}
	
	
	private void getTWMetrics(){
		
		//TODO: check if there's a twitter account 
		
		final LinearLayout graph3 = (LinearLayout)findViewById(R.id.graph3);
		final LinearLayout graph4 = (LinearLayout)findViewById(R.id.graph4);
		new TwitterMetrics(this).execute(graph3,graph4);
		
		new TWPostsMetrics(this).execute();
		
	}
	
	
	
	 private class TWPostsMetrics extends AsyncTask<Object, Void, ArrayList<HashMap<String,Object>>> {
		 
		 InsightsActivity caller;
			final ArrayList<HashMap<String,Object>> postss = new ArrayList<HashMap<String,Object>>();
		   	 
				public TWPostsMetrics(InsightsActivity callerActivity){
					caller=callerActivity;
				}
			 
			    @Override
			    protected ArrayList<HashMap<String,Object>> doInBackground(Object... param) {
			    	
			    	Log.w("ESA", "Calling Twitter Post Metrics...");
			    	
			    	String accessToken = "",accessTokenSecret="";
			    	
			    String s =new GlobalSettings(caller).getPrefString(GlobalSettings.PREF_TWITTER_TOKEN);
			    String [] t;
			    if(!s.equals("")){
			    t=s.split(";");
			    accessToken=t[0];
			    	accessTokenSecret=t[1];
			    }
			    	
			    	 ConfigurationBuilder cb = new ConfigurationBuilder();
					    cb.setDebugEnabled(true)
					          .setOAuthConsumerKey("RUMoRPLvEHqN9dPoFIiwQ")
					          .setOAuthConsumerSecret("krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE")
					          .setOAuthAccessToken(accessToken)
					          .setOAuthAccessTokenSecret(accessTokenSecret);
					    TwitterFactory tf = new TwitterFactory(cb.build());
					    Twitter twitter = tf.getInstance();
					    ResponseList<twitter4j.Status> twPosts;
	                   try {
						twPosts=	twitter.getUserTimeline(new Paging(1, 200));
						
				
							
					    for (twitter4j.Status status : twPosts) {					    	
					    	HashMap<String,Object> pp = new HashMap<String,Object>();
					    	
					    	pp.put("message", status.getCreatedAt().toString()+"\n"+status.getText());
					    	pp.put("rtc",status.getRetweetCount() + " Retweets");
					    	pp.put("favc",status.getFavoriteCount()+ " Favourites");
			        
			                postss.add(pp);
			            }
						
					   return postss;
					    
						
					} catch (TwitterException e1) {
					
						e1.printStackTrace();
					} 
					    
					
			      return null;
			    }

			    @Override
			    protected void onPostExecute(ArrayList<HashMap<String,Object>> result) {
			    	Log.w("ESA", "Exiting Twitter Post Metrics..." + result.size()+ "posts retrieved");
			    	ListView lv =(ListView)findViewById(R.id.tweetsList);
			    	fillTWList(result, lv);
			    }
			  }

		

	 private class TWHashtagMetrics extends AsyncTask<String, Void, ArrayList<HashMap<String,Object>>> {
		 
		 InsightsActivity caller;
			final ArrayList<HashMap<String,Object>> postss = new ArrayList<HashMap<String,Object>>();
		   	 
				public TWHashtagMetrics(InsightsActivity callerActivity){
					caller=callerActivity;
				}
				
			    @Override
			    protected ArrayList<HashMap<String,Object>> doInBackground(String... param) {
			    	
			    	Log.w("ESA", "Calling Twitter Hashtag Metrics...");
			    	
			    	String accessToken = "",accessTokenSecret="";
			    	
			    String s =new GlobalSettings(caller).getPrefString(GlobalSettings.PREF_TWITTER_TOKEN);
			    String [] t;
			    if(!s.equals("")){
			    t=s.split(";");
			    accessToken=t[0];
			    	accessTokenSecret=t[1];
			    }
			    	
			    	 ConfigurationBuilder cb = new ConfigurationBuilder();
					    cb.setDebugEnabled(true)
					          .setOAuthConsumerKey("RUMoRPLvEHqN9dPoFIiwQ")
					          .setOAuthConsumerSecret("krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE")
					          .setOAuthAccessToken(accessToken)
					          .setOAuthAccessTokenSecret(accessTokenSecret);
					    TwitterFactory tf = new TwitterFactory(cb.build());
					    Twitter twitter = tf.getInstance();
					  
						String queryString =param[0];
						try {
							Query query = new Query(queryString);
							
							QueryResult qresult;
							qresult = twitter.search(query);
							
							for (twitter4j.Status qstatus : qresult.getTweets()) {
							
					    	HashMap<String,Object> pp = new HashMap<String,Object>();
					    	
					    	pp.put("message",qstatus.getCreatedAt().toString()+"\n"+ qstatus.getUser().getScreenName()+" - "+ qstatus.getText());
					    	pp.put("rtc",qstatus.getRetweetCount() + " Retweets");
					    	pp.put("favc",qstatus.getFavoriteCount()+ " Favourites");
			      
			                postss.add(pp);
			            }
						
							if (postss.isEmpty()){
								
								HashMap<String,Object> pp = new HashMap<String,Object>();
						    	
						    	pp.put("message","No Tweet results for "+queryString);
						    	pp.put("rtc","");
						    	pp.put("favc","");
						    	 postss.add(pp);
							}
							
							
					   return postss;
					    
						
					} catch (TwitterException e1) {
					
						e1.printStackTrace();
					} 
					    
					
			      return null;
			    }

			    @Override
			    protected void onPostExecute(ArrayList<HashMap<String,Object>> result) {
			    	Log.w("ESA", "Exiting Twitter Hashtag Metrics..." + result.size()+ "posts retrieved");
			    	ListView lv =(ListView)findViewById(R.id.hashtagList);
			    	fillTWList(result, lv);
			    }
			  }

		
	
		public void hashtagMetrics(View v){
			
			EditText src =(EditText) findViewById(R.id.edtHashtag);
			if(gs.getPrefBool(gs.PREF_KEY_TWITTER_LOGIN))	
			new TWHashtagMetrics(this).execute(src.getText().toString());
			else{
				alert.showAlertDialog(this,
						"Not connected to Twitter",
						"You must have an active Twitter account associated to ESA to get the insights.", false);
			}
			
		}
		  
	
	

	
	 private class TwitterMetrics extends AsyncTask<Object, Void, Wrapper[]> {
			 
		 InsightsActivity caller;
				
				public TwitterMetrics(InsightsActivity callerActivity){
					caller=callerActivity;
				}
			 
			    @Override
			    protected Wrapper[] doInBackground(Object... param) {
			    	
			    	Log.w("ESA", "Calling TwitterMetrics... ");
			    	
			    	String accessToken = "",accessTokenSecret="";
			    	
			    String s =new GlobalSettings(caller).getPrefString(GlobalSettings.PREF_TWITTER_TOKEN);
			    String [] t;
			    if(!s.equals("")){
			    t=s.split(";");
			    accessToken=t[0];
			    	accessTokenSecret=t[1];
			    }
			    	
			    	 ConfigurationBuilder cb = new ConfigurationBuilder();
					    cb.setDebugEnabled(true)
					          .setOAuthConsumerKey("RUMoRPLvEHqN9dPoFIiwQ")
					          .setOAuthConsumerSecret("krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE")
					          .setOAuthAccessToken(accessToken)
					          .setOAuthAccessTokenSecret(accessTokenSecret);
					    TwitterFactory tf = new TwitterFactory(cb.build());
					    Twitter twitter = tf.getInstance();
					    ResponseList<twitter4j.Status> twMentions;
					    ResponseList<twitter4j.Status> twStatuses;
	                   try {
						int nFollowers = twitter.verifyCredentials().getFollowersCount();
						String usrname = twitter.getScreenName();
						twStatuses=twitter.getUserTimeline(new Paging(1, 100));
						twMentions=	twitter.getMentionsTimeline(new Paging(1, 100));
						
						HashMap<Date, Object> mentionsData = new HashMap<Date, Object>();
						Date d;
						DateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd");
						
						Calendar c = Calendar.getInstance();
						c.add(Calendar.MONTH,-1);
							
					    for (twitter4j.Status status : twMentions) {
			               // System.out.println("@" + status.getUser().getScreenName() + " - " +status.getCreatedAt()+"--" + status.getText());
					    	 d=   outputFormatter.parse(outputFormatter.format(status.getCreatedAt()));
					    	if (c.getTime().before(d)){ //get only statuses created in the last month
			               
			                if( mentionsData.containsKey(d))
			                	mentionsData.put(d,(Double) mentionsData.get(d) + 1); 
			                else
			                	mentionsData.put(d,(double) 1);
			                }
			            }
					    
					
						
					    Date[] keys = new Date[mentionsData.size()];
					    double[] values = new double[mentionsData.size()];
					    int index = 0;
					    for (Entry<Date, Object> mapEntry : mentionsData.entrySet()) {
					        keys[index] = mapEntry.getKey();
					        values[index] = (Double) mapEntry.getValue();
					        index++;
					    }
					    Wrapper[] wrappers= new Wrapper[2];
					    
					    Wrapper w = new Wrapper(values, keys,usrname, nFollowers,(LinearLayout)param[0]);
					    wrappers[0]=w;
					    
					    for (twitter4j.Status status : twStatuses) {
				               
			                d=   outputFormatter.parse(outputFormatter.format(status.getCreatedAt()));
			                if (c.getTime().before(d)){ //get only statuses created in the last month
			                if( mentionsData.containsKey(d))
			                	mentionsData.put(d,(Double) mentionsData.get(d) + (double) status.getRetweetCount()+(double) status.getFavoriteCount());
			                else
			                	mentionsData.put(d,(double) status.getRetweetCount()+(double) status.getFavoriteCount());
			                }
			            }
					
					    Date[] keys2 = new Date[mentionsData.size()];
					    double[] values2 = new double[mentionsData.size()];
					     index = 0;
					    for (Entry<Date, Object> mapEntry : mentionsData.entrySet()) {
					        keys2[index] = mapEntry.getKey();
					        values2[index] = (Double) mapEntry.getValue();
					        index++;
					    }
					    
					    Wrapper w2 = new Wrapper(values2, keys2,usrname, nFollowers,(LinearLayout)param[1]);
					    wrappers[1]=w2;
					    
					    return wrappers;
						
					} catch (TwitterException e1) {

						e1.printStackTrace();
					} catch (ParseException e) {

						e.printStackTrace();
					}
					    
					
			      return null;
			    }

			    @Override
			    protected void onPostExecute(Wrapper[] result) {
			    	Log.w("ESA", "Exiting TwitterMetrics... ");
			    	if(result!=null){
			    		Log.w("ESA", "...result not null");
			    	TextView t= (TextView)findViewById(R.id.txtNumFollowers);
			    	t.setText("@"+result[0].usrName+" - "+ result[0].nFollowers + " Followers");
			    	createGraph(result[0].values, result[0].dates,result[0].graphLayout);
			    	createGraph(result[1].values, result[1].dates,result[1].graphLayout);
			    	}
			    }
			  }

		
		
	
	
	
	
	
	
	private void getFBMetrics(){
		//getting ids of the layouts where the graph will be drawn
		final LinearLayout graph1 = (LinearLayout)findViewById(R.id.graph1);
		final LinearLayout graph2 = (LinearLayout)findViewById(R.id.graph2);
		
		final String id = new GlobalSettings(this).getPrefString(GlobalSettings.PREF_KEY_FACEBOOK_ID);
		
		if(id!=""){ //ok i've added a page to ESA
			
			Session.openActiveSession(this, true, new Session.StatusCallback() {

				// callback when session changes state
				@Override
				public void call(Session session, SessionState state,
						Exception exception) {

					if (session.isOpened()) {
						
						
						
						Calendar c = Calendar.getInstance();
						c.add(Calendar.MONTH,-1);
						c.add(Calendar.DAY_OF_MONTH,-2);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String since = sdf.format(c.getTime());
						
						String grapPath = id+"/insights/page_engaged_users"; // first Metric
						String grapPath2 = id+"/insights/page_impressions_unique";// second Metric
						Bundle params = new Bundle();
						params.putString("since",since);
						
						
						Request request = new Request(session, grapPath,
								params, HttpMethod.GET, new Callback() {

									@Override
									public void onCompleted(Response response) {
										if (response != null) {
											GraphObject graphObject = response.getGraphObject();
											new deserializeFB(InsightsActivity.this).execute(graphObject,graph2);
										}

									}
								});

						RequestAsyncTask task = new RequestAsyncTask(request);
						task.execute();
						
						
						Request request2 = new Request(session, grapPath2,
								params, HttpMethod.GET, new Callback() {

									@Override
									public void onCompleted(Response response) {
										if (response != null) {
											GraphObject graphObject = response.getGraphObject();
											new deserializeFB(InsightsActivity.this).execute(graphObject,graph1);
										}

									}
								});

						RequestAsyncTask task2 = new RequestAsyncTask(request2);
						task2.execute();
						
					
					//Getting page posts IDs and Messages
						String req = id+"/posts";
						Bundle param = new Bundle();
						params.putString("limit","50");
						Request postsRequest = new Request(session, req,
								param, HttpMethod.GET, new Callback() {

									@Override
									public void onCompleted(Response response) {
										if (response != null) {
											
											GraphObject graphObject = response.getGraphObject();
											//new deserializeFB(InsightsActivity.this).execute(graphObject,graph1);
										
											  if (graphObject != null) {
												  
									      		   JSONObject  jsonObject = graphObject.getInnerJSONObject();
									      		   JSONArray array;
									   				try {
									   						array = jsonObject.getJSONArray("data");
									   						postsInsights[] p= new postsInsights[array.length()];		
									   						
									   						for (int i = 0; i < array.length(); i++) {
									   							JSONObject obj = (JSONObject) array.get(i);
									   							if(obj.has("message")){
									   							p[i]=  new postsInsights();
									   							p[i].message=(String) obj.get("message");
									   							p[i].postID=(String) obj.get("id");}
									   						}
									   						
									   					 doBatchRequest(p);//calling method for posts insights
									   							
									   				}
									   				catch (JSONException e) {
														
														e.printStackTrace();
													}
									   				
											  }
										}

									}
								});

						RequestAsyncTask postsTask= new RequestAsyncTask(postsRequest);
						postsTask.execute();
						
						
						
					}
				}
			});
			
			
			
	 }// (id!="")
	}
	

	
	//for each post make a call to get insights metrics.
	private void doBatchRequest(final postsInsights[] p) {
	   
		final TextView	 textViewResults = (TextView) InsightsActivity.this.findViewById(R.id.txtLoadingIns);
		
	   // String[] requestIds = {"me", "4"};
		//final ArrayList<postsInsights> posts = new ArrayList<postsInsights>();
		final ArrayList<HashMap<String,Object>> postss = new ArrayList<HashMap<String,Object>>();
   
	    RequestBatch requestBatch = new RequestBatch();
	    
	    for (int i=0;i<p.length;i++) {
	    	if(p[i]!= null){
	    		
	    	
	    	final String pID =p[i].postID+"/insights";
	    	final postsInsights post=p[i];
	    	
	        requestBatch.add(new Request(Session.getActiveSession(), 
	        		pID, null, null, new Request.Callback() {
	            public void onCompleted(Response response) {
	            	
	                GraphObject graphObject = response.getGraphObject();	 
	                String s = textViewResults.getText().toString();
	                if (graphObject != null) {	                  
	                	 JSONObject  jsonObject = graphObject.getInnerJSONObject();

	                     JSONArray array,values;
	    				try {
	    					array = jsonObject.getJSONArray("data");
	    					
	    					
	    					for(int i = 0 ; i < array.length() ; i++){
	    						String metric= array.getJSONObject(i).getString("name");
	    						if(metric.equals("post_impressions_unique"))
	    								{	JSONObject object =  array.getJSONObject(i);
	    		    					values=object.getJSONArray("values");
	    		    					JSONObject obj =  values.getJSONObject(0);	    						
	    		                    	post.reach=(Integer) obj.get("value"); }
	    						
	    						if(metric.equals("post_story_adds"))
								{	JSONObject object =  array.getJSONObject(i);
		    					values=object.getJSONArray("values");
		    					JSONObject obj =  values.getJSONObject(0);	    						
		    					post.lcs=(Integer) obj.get("value"); }
	    						
	    						if(metric.equals("post_consumptions"))
								{	JSONObject object =  array.getJSONObject(i);
		    					values=object.getJSONArray("values");
		    					JSONObject obj =  values.getJSONObject(0);	    						
		    					post.clicks=(Integer) obj.get("value"); }
	    						
	    					}
	    					
	    				/*	
	    					
	    					JSONObject object =  array.getJSONObject(4);
	    					values=object.getJSONArray("values");
	    					JSONObject obj =  values.getJSONObject(0);	    						
	                    	post.reach=(Integer) obj.get("value"); //("post_impressions_unique");//4
	                    	
	                    	

	    					
	                    	
	                    	object = (JSONObject) array.get(1);
	    					values=object.getJSONArray("values");
	    					 obj = (JSONObject) values.get(0);	
	                    	post.lcs=(Integer) obj.get("value");//("post_story_adds");//1		              
	                    	
	                    	
	                    	 object = (JSONObject) array.get(19);
	                    	  String str =(String)object.get("name");
	                    	 if(str.equals("post_consumptions")){
		    					values=object.getJSONArray("values");
		    					 obj = (JSONObject) values.get(0);	
		                    	post.clicks=(Integer) obj.get("value");//("post_consumptions");//19
		                    	}
	                    	 else{//FIX for posts prior to may 1st.
	                    		 object = (JSONObject) array.get(15);
	                    		 values=object.getJSONArray("values");
		    					 obj = (JSONObject) values.get(0);	
		                    	post.clicks=(Integer) obj.get("value");//("post_consumptions");//15
		                    	
	                    	 }
		                    	*/
	    					
	                    	 HashMap<String,Object> pp = new HashMap<String,Object>();
	                    	 pp.put("message", post.message);
	                    	 pp.put("reach", "Reach:"+post.reach);
	                    	 pp.put("clicks","Post clicks:"+ post.clicks);
	                    	 pp.put("lcs", "Likes, comments & shares:"+post.lcs);
	                    	postss.add(pp);
	                    	
	                    	
	                    	// s = s +">>"+post.message+" Reach:"+post.reach+" Clicks:"+post.clicks+" lcs:"+post.lcs+  "\n";
	    				}
	    				 catch (JSONException e1) {
	    	   					
	    	   					e1.printStackTrace();
	    	   				}   
	    				 catch (ClassCastException ex) {
	    	   					
	    	   					ex.printStackTrace();
	    	   				}   
	                }
	                
	            }
	        }));
	    }
	    }
	    
	    requestBatch.addCallback(new com.facebook.RequestBatch.Callback() {
            @Override
            public void onBatchCompleted(RequestBatch batch) {
                textViewResults.setText("");

            	fillList(postss);
            }
        });
	    
	    requestBatch.executeAsync();
	    
	    
	}
	
	
	 private class deserializeFB extends AsyncTask<Object, Void, Wrapper> {
		 
		 InsightsActivity caller;
			
			 
			public deserializeFB(InsightsActivity callerActivity){
				caller=callerActivity;
				
			}
		 
		    @Override
		    protected Wrapper doInBackground(Object... param) {
		    	Log.w("ESA", "Calling Deserialize FB... ");
		    	
		    	GraphObject graphObject =(GraphObject)param[0];
        	   if (graphObject != null) {
      		   JSONObject  jsonObject = graphObject.getInnerJSONObject();
      		   	
                    JSONArray array,values;
   				try {
   						array = jsonObject.getJSONArray("data");
   						JSONObject object = (JSONObject) array.get(0);
   						values=object.getJSONArray("values");
   						
   						double[] val = new double[values.length()];
   						Date[] dat = new Date[values.length()];
   						DateFormat formatter = new  SimpleDateFormat("yyyy-MM-dd");
   					
   						for (int i = 0; i < values.length(); i++) {
   							
   						
   	                         JSONObject obj = (JSONObject) values.get(i);
   	                       val[i]=(Integer) obj.get("value");
   	                       dat[i]= formatter.parse(obj.get("end_time").toString().split("T")[0]);
   						}
   					
   						Wrapper w = new Wrapper(val, dat,"",0,(LinearLayout)param[1]);
   						return w;
            	//createGraph(val,dat);
                    
   				}
                    
   				 catch (JSONException e1) {
   					
   					e1.printStackTrace();
   				}   	
   				catch (ParseException e) {
					
					e.printStackTrace();
				}
   				
//   				fillList(FeedData);
        	   }
		   	 
		   	
			return null;
		    	
		    }
		    
		  
		    protected void onPostExecute(Wrapper result) {
		    	Log.w("ESA", "Exiting Deserialize FB... " + result.graphLayout.toString());
		    	t1.setText("The number of people who have seen any content associated with your Page in the last month.");
				t2.setText("The number of people who engaged with your Page in the last month. Engagement includes any click or story created.");
		    	createGraph(result.values, result.dates,result.graphLayout);
		     }
	 }
	 
	  public class Wrapper {
		  String usrName;
		  int nFollowers;
	    	double[] values;
	    	Date[] dates; 
	    	LinearLayout graphLayout;
	    	public Wrapper(double[] val,Date[] dat,String usrn, int nfollow,LinearLayout l){
	    		
	    		values=val;
	    		dates=dat;
	    		usrName=usrn;
	    		nFollowers=nfollow;
	    		graphLayout=l;
	    	}
	     }
	 
	  
	  public class postsInsights{
		  
		  String postID,message;
		  Integer reach,clicks,lcs;
	  }
	 
	  
	  

		public void fillTWList( ArrayList<HashMap<String,Object>> data,ListView lv){
			
			
			String[] from = { "message", "rtc", "favc"}; // from values of hashMap
			int[] to = { R.id.lstTwMsg, R.id.txtRt, R.id.txtFav};// to id of view
		      
			SimpleAdapter  adapter=new SimpleAdapter(
	                       this,
	                        data,//data source
	                        R.layout.tw_insights_element, //layout of a single feed element
	                        from,
	                        to);
			
	      lv.setAdapter(adapter);
	      adapter.notifyDataSetChanged();
	    
	        
	  	
			}
		

		public void fillList( final ArrayList<HashMap<String,Object>> data){
			
			
			  ListView lv =(ListView)findViewById(R.id.insightList);
		
			String[] from = { "message", "reach", "clicks", "lcs"}; // from values of hashMap
			int[] to = { R.id.lstMsg, R.id.txtReach, R.id.txtClicks,R.id.txtLCS};// to id of view
		      
			SimpleAdapter  adapter=new SimpleAdapter(
	                       this,
	                        data,//data source
	                        R.layout.insight_element, //layout of a single feed element
	                        from,
	                        to);
			
	      lv.setAdapter(adapter);
	      adapter.notifyDataSetChanged();
	    
	      lv.setOnItemLongClickListener(new OnItemLongClickListener() {

	          public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
	                  int pos, long id) {
	              // TODO Auto-generated method stub

	             HashMap<String, Object> elem=data.get(pos);
	            AlertDialog.Builder dialog = new AlertDialog.Builder(InsightsActivity.this);
	           // dialog.setTitle(elem.get("tagger").toString());
	            dialog.setMessage(elem.get("message").toString());
	          
	            dialog.show();
	       
	              return true;
	          }
	      }); 
	  	
			}
			
			

	  
	 public void createGraph(double[] val,Date[] dat,LinearLayout graphLayout)
			 {
				 
				 GraphicalView gView = this.getView(this.getApplicationContext(), val,dat);
				 
	            //	LinearLayout l= (LinearLayout)findViewById(R.id.graph1);
	            	//l.addView(gView);
				 graphLayout.addView(gView);
			 }
	
	 public GraphicalView getView(Context context,double[] val,Date[] dat){
		 
		 
		  TimeSeries series = new TimeSeries("");                          
          for (int k=0; k<val.length;k++)
          	series.add(dat[k],val[k]);
          
          XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
          dataset.addSeries(series);
          
          XYSeriesRenderer renderer = new XYSeriesRenderer();
          FillOutsideLine fill = new FillOutsideLine(XYSeriesRenderer.FillOutsideLine.Type.BOUNDS_ALL);
          fill.setColor(Color.argb(200, 230, 152,28));
          renderer.addFillOutsideLine(fill);
          renderer.setDisplayBoundingPoints(true);
          renderer.setLineWidth(2);
          renderer.setColor(Color.RED);
       
          XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
          mRenderer.setXRoundedLabels(true);
          mRenderer.setYLabels(5);
          mRenderer.setYLabelsColor(0, Color.RED);
          mRenderer.setXLabelsAngle(45);
          mRenderer.setXLabelsPadding(18);
          mRenderer.setYLabelsPadding(10);
          mRenderer.addSeriesRenderer(renderer);
          mRenderer.setLabelsTextSize(16.0f);
          mRenderer.setApplyBackgroundColor(true);
          mRenderer.setLegendTextSize(16);
          mRenderer.setPanEnabled(false, false);
          mRenderer.setZoomRate(0.2f);
          mRenderer.setZoomEnabled(false, false);
         // mRenderer.setBackgroundColor(Color.BLACK);
          
          mRenderer.setAxesColor(Color.CYAN);
          
          
        return ChartFactory.getTimeChartView(InsightsActivity.this.getApplicationContext(), dataset, mRenderer,"time");
		 
	 }

	

}
